#!/bin/bash
#
# 本文件是通过 msys64 环境（Windows 子系统 for Linux）运行的，
# 故有一些命令的路径需要注意，以及一些 shell 脚本，默认在 windows 下无法运行，需要阅读后，进行适当改写才能在 windows cmd 命令下运行。
# 
# Complete training and deployment pipeline for the Iris classifier.
# This script demonstrates the best practices for BentoML model management
# following the same steps as train_and_deploy.py.
#

set -e  # Exit on any error

echo "=== Iris Classifier Training and Deployment Pipeline ==="

export bentoimage=bentoml1:0.1

# Activate virtual environment
echo "Activating virtual environment..."
## for windows msys2
source .venv/Scripts/activate
## for ubuntu/linux
# source .venv/bin/activate

# Train new model
echo "Step 1/4: Training new Iris classifier model..."
python development/train_model.py

# Update latest tag
echo "Step 2/4: [Optional] Updating 'latest' tag..."
python development/update_latest.py

# Build Bento
echo "Step 3/4: Building Bento package..."
bentoml build

# Get the latest Bento tag
BENTO_TAG=$(bentoml list | grep iris_classifier | head -1 | awk '{print $1}')
echo "Built Bento: $BENTO_TAG"

# Containerize Bento
echo "Step 4/4: Creating Docker image..."
echo "NOTE!!!!! 主机必须可以直接调用 docker 命令，即设置好当前用户也属于 docker 组（通过 `sudo usermod -aG docker $USER` 并重启 docker 和注销当前session实现的）；另外这一步超级慢"
# bentoml containerize "$BENTO_TAG" -t docker.io/library/$bentoimage
bentoml containerize "$BENTO_TAG" -t $bentoimage

# Import image to k3d
echo "Importing Docker image to k3d..."
echo "NOTE!!!!!! 需要提前创建好有着加速器 registries.yaml 文件的 k3d 环境。"
k3d image import $bentoimage

# Restart deployment
echo "Apply or Rollout restart to new version."
# kubectl rollout restart deployment/iris-classifier
kubectl apply -f iris_api.yaml
# Wait for deployment to be ready
echo "Waiting for deployment to be ready..."
kubectl wait --for=condition=ready pod -l app=iris-classifier --timeout=120s

echo "=== Pipeline completed successfully ==="
echo "Model: $(bentoml models list | grep iris_clf | head -1 | awk '{print $1}')"
echo "Bento: $BENTO_TAG"
echo "Image: docker.io/library/$bentoimage"
echo ""
echo "You can now access the API documentation at: http://localhost:8081"
echo "Test the API with: curl -X POST http://localhost:8081/classify   -H 'Content-Type: application/json'  -d '{\"input_data\": [[5.1, 3.5, 1.4, 0.2]]}'"